package com.chase.passwordmaster.utils

import android.util.Base64
import com.chase.passwordmaster.encoder.encoder_v2.EncoderV2
import com.chase.passwordmaster.encoder.encoder_v2.EncoderV2.toPublicKey
import com.chase.passwordmaster.encoder.encoder_v2.EncoderV2.toPrivateKey
import java.lang.Exception
import java.security.PrivateKey
import javax.crypto.Cipher

/**
 * 该公钥是合法的RSA公钥？
 * Is the key a valid public key?
 *
 * @param key      待验证公钥
 * @return Boolean 是合法公钥
 */
fun isValidPublicKey(key: String): Boolean {
    if (key.isEmpty()) {
        return false
    }

    return try {
        key.toPublicKey()
        true
    } catch (e: Exception) {
        false
    }
}

/**
 * 该私钥是合法的RSA公钥？
 * Is the key a valid private key?
 *
 * @param key      待验证私钥
 * @return Boolean 是合法私钥
 */
fun isValidPrivateKey(key: String): Boolean {
    if (key.isEmpty()) {
        return false
    }

    return try {
        key.toPrivateKey()
        true
    } catch (e: Exception) {
        false
    }
}

/**
 * 将内容使用RSA公钥publicKey加密
 * Encrypt content by RSA
 *
 * @param content         待加密内容
 * @param publicKeyString 用于加密的String形式的RSA公钥
 */
fun encryptByRSA(content: String, publicKeyString: String) = EncoderV2.encryptByRSA(content, publicKeyString)

/**
 * 将内容按照privateKey解密
 * Decrypt content by RSA
 *
 * @param content          待解密内容
 * @param privateKeyString 用于解密的String形式的RSA私钥
 */
fun decryptByRSA(content: String, privateKeyString: String) =
    String(
        content.base64Decrypted().rsaDecrypted(
            privateKeyString.toPrivateKey()
        )
    )

/**
 * Decrypt BASE64 into ByteArray
 */
fun String.base64Decrypted(): ByteArray = Base64.decode(this, Base64.DEFAULT)

/**
 * Decrypt content format in ByteArray
 */
private fun ByteArray.rsaDecrypted(privateKey: PrivateKey): ByteArray {
    val cipher = Cipher.getInstance("RSA")
    cipher.init(Cipher.DECRYPT_MODE, privateKey)
    return cipher.doFinal(this)
}